﻿using System.Windows.Controls;
using IMClient.ViewModels;

namespace IMClient.View
{
    public partial class ChatView : UserControl
    {
        public ChatView()
        {
            InitializeComponent();
            DataContextChanged += ChatView_DataContextChanged;
            Unloaded += UserControl_Unloaded;
        }

        private void ChatView_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if (e.OldValue is ChatPageViewModel oldVM)
            {
                oldVM.ScrollToBottomRequested -= ChatViewModel_ScrollToBottomRequested!;
            }

            if (e.NewValue is ChatPageViewModel newVM)
            {
                newVM.ScrollToBottomRequested += ChatViewModel_ScrollToBottomRequested!;
            }
        }

        private void ChatViewModel_ScrollToBottomRequested(object sender, EventArgs e)
        {
            // 使用 Dispatcher 确保在 UI 线程上执行
            Dispatcher.BeginInvoke(new Action(() =>
            {
                ChatScrollViewer.ScrollToBottom();
            }));
        }

        private void UserControl_Unloaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (DataContext is ChatPageViewModel vm)
            {
                vm.ScrollToBottomRequested -= ChatViewModel_ScrollToBottomRequested!;
            }
        }
    }
}
